<div class="tmd-doc">
<h1 class="tmd-header-1">
Arrays, Slices and Maps in Go
</h1>
<p></p>
<div class="tmd-usual">
Strictly speaking, there are three kinds of first-class citizen container types in Go, array, slice and map. Sometimes, strings and channels can also be viewed as container types, but this article will not touch the two kinds of types. All container types talked about in the current article are arrays, slices and maps.
</div>
<p></p>
<div class="tmd-usual">
There are many container related details in Go. This article will list them one by one.
</div>
<p></p>
<h3 class="tmd-header-3">
Simple Overview of Container Types and Values
</h3>
<p></p>
<div class="tmd-usual">
Each value of the three kinds of types is used to store a collection of element values. The types of all the elements stored in a container value are identical. The identical type is called the element type of (the container type of) the container value.
</div>
<p></p>
<div class="tmd-usual">
Each element in a container has an associated key. An element value can be accessed or modified through its associated key. The key types of map types must be <a href="type-system-overview.html#types-not-support-comparison">comparable types</a>. The key types of array and slice types are all the built-in type <code class="tmd-code-span">int</code>. The keys of the elements of an array or slice are non-negative integers which mark the positions of these elements in the array or slice. The non-negative integer keys are often called indexes.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Each container value has a length property, which indicates how many elements are stored in that container. The valid range of the integer keys of an array or slice value is from zero (inclusive) to the length (exclusive) of the array or slice. For each value of a map type, the key values of that map value can be an arbitrary value of the key type of the map type.
</div>
<p></p>
<div class="tmd-usual">
There are also many differences between the three kinds of container types. Most of the differences originate from the differences between the value memory layouts of the three kinds of types. From the last article, <a href="value-part.html">value parts</a>, we learned that an array value consists of only one direct part, however a slice or map value may have an underlying part, which is referenced by the direct part of the slice or map value.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Elements of an array or a slice are both stored contiguously in a continuous memory segment. For an array, the continuous memory segment hosts the direct part of the array. For a slice, the continuous memory segment hosts the underlying indirect part of the slice. The map implementation of the standard Go compiler/runtime adopts the hashtable algorithm. So all elements of a map are also stored in an underlying continuous memory segment, but they may be not contiguous. There may be many holes (gaps) within the continuous memory segment. Another common map implementation algorithm is the binary tree algorithm. Whatever algorithm is used, the keys associated with the elements of a map are also stored in (the underlying parts of) the map.
</div>
<p></p>
<div class="tmd-usual">
We can access an element through its key. The time complexities of element accesses on all container values are all <span class="tmd-italic"><code class="tmd-code-span">O(1)</code></span>, though, generally map element accesses are several times slower than array and slice element accesses. But maps have two advantages over arrays and slices:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
the key types of maps can be any comparable types.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
maps consume much less memory than arrays and slices if most elements are zero values.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
From the last article, we have learned that the underlying parts of a value will not get copied when the value is copied. In other words, if a value has underlying parts, a copy of the value will share the underlying parts with the value. This is the root reason of many behavior differences between array and slice/map values. These behavior differences will be introduced below.
</div>
<p></p>
<h3 class="tmd-header-3">
Literal Representations of Unnamed Container Types
</h3>
<p></p>
<div class="tmd-usual">
The literal representations of the three kinds of unnamed container types:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
array types: <code class="tmd-code-span">[N]T</code>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
slice types: <code class="tmd-code-span">[]T</code>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
map types: <code class="tmd-code-span">map[K]T</code> where
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">T</code> is an arbitrary type. It specifies the element type of a container type. Only values of the specified element type can be stored as element values of values of the container type.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">N</code> must be a non-negative integer constant. It specifies the number of elements stored in any value of an array type, and it can be called the length of the array type. This means the length of an array type is the inherent part of the array type. For example, <code class="tmd-code-span">[5]int</code> and <code class="tmd-code-span">[8]int</code> are two distinct array types.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<code class="tmd-code-span">K</code> is an arbitrary comparable type. It specifies the key type of a map type. Most types in Go are comparable, incomparable types are <a href="type-system-overview.html#types-not-support-comparison">listed here</a>.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
Here are some container type literal representation examples:
</div>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">const Size = 32

type Person struct {
	name string
	age  int
}

/* Array types */

[5]string
[Size]int
// Element type is a slice type: []byte
[16][]byte
// Element type is a struct type: Person
[100]Person

/* Slice types */

[]bool
[]int64
// Element type is a map type: map[int]bool
[]map[int]bool
// Element type is a pointer type: *int
[]*int

/* Map types */

map[string]int
map[int]bool
// Element type is an array type: [6]string
map[int16][6]string
// Element type is a slice type: []string
map[bool][]string
// Element type is a pointer type: *int8,
// and key type is a struct type.
map[struct{x int}]*int8
</code></pre>
<p></p>
<div class="tmd-usual">
The <a href="type-system-overview.html#value-size">sizes</a> of all slice types are the same. The sizes of all map types are also the same. The size of an array type depends on its length and the size of its element type. The size of a zero-length array type or an array type with a zero-size element type is zero.
</div>
<p></p>
<p></p>
<h3 id="value-literals" class="tmd-header-3">
Container Value Literals
</h3>
<p></p>
<div class="tmd-usual">
Like struct values, container values can also be represented with composite literals, <code class="tmd-code-span">T{...}</code>, where <code class="tmd-code-span">T</code> denotes container type (except the zero values of slice and map types). Here are some examples:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">// An array value containing four bool values.
[4]bool{false, true, true, false}

// A slice value which contains three words.
[]string{"break", "continue", "fallthrough"}

// A map value containing some key-value pairs.
map[string]int{"C": 1972, "Python": 1991, "Go": 2009}
</code></pre>
<p></p>
<div class="tmd-usual">
Each key-element pair between the braces of a map composite literal is also called an entry.
</div>
<p></p>
<div class="tmd-usual">
There are several variants for array and slice composite literals:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">
// The followings slice composite literals
// are equivalent to each other.
[]string{"break", "continue", "fallthrough"}
[]string{0: "break", 1: "continue", 2: "fallthrough"}
[]string{2: "fallthrough", 1: "continue", 0: "break"}
[]string{2: "fallthrough", 0: "break", "continue"}

// The followings array composite literals
// are equivalent to each other.
[4]bool{false, true, true, false}
[4]bool{0: false, 1: true, 2: true, 3: false}
[4]bool{1: true, true}
[4]bool{2: true, 1: true}
[...]bool{false, true, true, false}
[...]bool{3: false, 1: true, true}
</code></pre>
<p></p>
<div class="tmd-usual">
In the last two literals, the <code class="tmd-code-span">...</code>s mean we want to let compilers deduce the lengths for the corresponding array values.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
From the above examples, we know that element indexes (keys) are optional in array and slice composite literals. In an array or slice composite literal,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if an index is present, it is not needed to be a typed value of the key type <code class="tmd-code-span">int</code>, but it must be a non-negative constant representable as a value of type <code class="tmd-code-span">int</code>. And if it is typed, its type must be a <a href="basic-types-and-value-literals.html#overview">basic integer type</a>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
<span class="tmd-bold">an element which index is absent uses the previous element's index plus one as its index.</span>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if the index of the first element is absent, its index is zero.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
The keys of entries in a map literal must not be absent, they can be non-constants.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var a uint = 1
var _ = map[uint]int {a : 123} // okay

// The following two lines fail to compile,
// for "a" is not a constant key/index.
var _ = []int{a: 100}  // error
var _ = [5]int{a: 100} // error
</code></pre>
<p></p>
<div class="tmd-usual">
Constant keys in one specific composite literal <a href="details.html#constant-keys-in-composite-literals">can't be duplicate</a>.
</div>
<p></p>
<p></p>
<h3 class="tmd-header-3">
Literal Representations of Zero Values of Container Types
</h3>
<p></p>
<div class="tmd-usual">
Like structs, the zero value of an array type <code class="tmd-code-span">A</code> can be represented with the composite literal <code class="tmd-code-span">A{}</code>. For example, the zero value of type <code class="tmd-code-span">[100]int</code> can be denoted as <code class="tmd-code-span">[100]int{}</code>. All elements stored in the zero value of an array type are zero values of the element type of the array type.
</div>
<p></p>
<div class="tmd-usual">
Like pointer types, zero values of all slice and map types are represented with the predeclared <code class="tmd-code-span">nil</code>.
</div>
<p></p>
<div class="tmd-usual">
BTW, there are some other kinds of types whose zero values are also represented by <code class="tmd-code-span">nil</code>, including later to be introduced function, channel and interface types.
</div>
<p></p>
<div class="tmd-usual">
When an array variable is declared without being specified an initial value, memory has been allocated for the elements of the zero array value. The memory for the elements of a nil slice or map value has not been allocated yet.
</div>
<p></p>
<div class="tmd-usual">
Please note, <code class="tmd-code-span">[]T{}</code> represents a blank slice value (with zero elements) of slice type <code class="tmd-code-span">[]T</code>, it is different from <code class="tmd-code-span">[]T(nil)</code>. The same situation is for <code class="tmd-code-span">map[K]T{}</code> and <code class="tmd-code-span">map[K]T(nil)</code>.
</div>
<p></p>
<h3 id="take-composite-literal-address" class="tmd-header-3">
Composite Literals Are Unaddressable but Can Be Taken Addresses
</h3>
<p></p>
<div class="tmd-usual">
We have learned that <a href="struct.html#take-composite-literal-address">struct composite literals can be taken addresses directly</a> before. Container composite literals have no exceptions here.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	pm := &amp;map[string]int{"C": 1972, "Go": 2009}
	ps := &amp;[]string{"break", "continue"}
	pa := &amp;[...]bool{false, true, true, false}
	fmt.Printf("%T\n", pm) // *map[string]int
	fmt.Printf("%T\n", ps) // *[]string
	fmt.Printf("%T\n", pa) // *[4]bool
}
</code></pre>
<p></p>
<h3 id="composite-literal-simplification" class="tmd-header-3">
Nested Composite Literals Can Be Simplified
</h3>
<p></p>
<div class="tmd-usual">
If a composite literal nested many other composite literals, then those nested composited literals can simplified to the form <code class="tmd-code-span">{...}</code>.
</div>
<p></p>
<div class="tmd-usual">
For example, the slice value literal
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">
// A slice value of a type whose element type is
// *[4]byte. The element type is a pointer type
// whose base type is [4]byte. The base type is
// an array type whose element type is "byte".
var heads = []*[4]byte{
	&amp;[4]byte{'P', 'N', 'G', ' '},
	&amp;[4]byte{'G', 'I', 'F', ' '},
	&amp;[4]byte{'J', 'P', 'E', 'G'},
}
</code></pre>
<p></p>
<div class="tmd-usual">
can be simplified to
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var heads = []*[4]byte{
	{'P', 'N', 'G', ' '},
	{'G', 'I', 'F', ' '},
	{'J', 'P', 'E', 'G'},
}
</code></pre>
<p></p>
<div class="tmd-usual">
The array value literal in the following example
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">type language struct {
	name string
	year int
}

var _ = [...]language{
	language{"C", 1972},
	language{"Python", 1991},
	language{"Go", 2009},
}
</code></pre>
<p></p>
<div class="tmd-usual">
can be simplified to
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var _ = [...]language{
	{"C", 1972},
	{"Python", 1991},
	{"Go", 2009},
}
</code></pre>
<p></p>
<div class="tmd-usual">
And the map value literal in the following example
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">type LangCategory struct {
	dynamic bool
	strong  bool
}

// A value of map type whose key type is
// a struct type and whose element type
// is another map type "map[string]int".
var _ = map[LangCategory]map[string]int{
	LangCategory{true, true}: map[string]int{
		"Python": 1991,
		"Erlang": 1986,
	},
	LangCategory{true, false}: map[string]int{
		"JavaScript": 1995,
	},
	LangCategory{false, true}: map[string]int{
		"Go":   2009,
		"Rust": 2010,
	},
	LangCategory{false, false}: map[string]int{
		"C": 1972,
	},
}
</code></pre>
<p></p>
<div class="tmd-usual">
can be simplified to
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var _ = map[LangCategory]map[string]int{
	{true, true}: {
		"Python": 1991,
		"Erlang": 1986,
	},
	{true, false}: {
		"JavaScript": 1995,
	},
	{false, true}: {
		"Go":   2009,
		"Rust": 2010,
	},
	{false, false}: {
		"C": 1972,
	},
}
</code></pre>
<p></p>
<div class="tmd-usual">
Please notes, in the above several examples, the comma following the last item in each composite literal can't be omitted. Please read <a href="line-break-rules.html">the line break rules in Go</a> for more information later.
</div>
<p></p>
<p></p>
<h3 id="comparison" class="tmd-header-3">
Compare Container Values
</h3>
<p></p>
<div class="tmd-usual">
As which has mentioned in the article <a href="type-system-overview.html#types-not-support-comparison">overview of Go type system</a>, map and slice types are incomparable types. So map and slice types can't be used as map key types.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Although a slice or map value can't be compared with another slice or map value (or itself), it can be compared to the bare untyped <code class="tmd-code-span">nil</code> identifier to check whether or not the slice or map value is a zero value.
</div>
<p></p>
<div class="tmd-usual">
Most array types are comparable, except the ones whose element types are incomparable types.
</div>
<p></p>
<div class="tmd-usual">
When comparing two array values, each pair of the corresponding elements will be compared. We can think element pairs are compared by their index order. The two array values are equal only if all of their corresponding elements are equal. The comparison stops in advance when a pair of elements is found unequal or <a href="interface.html#comparison">a panic occurs</a>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var a [16]byte
	var s []int
	var m map[string]int

	fmt.Println(a == a)   // true
	fmt.Println(m == nil) // true
	fmt.Println(s == nil) // true
	fmt.Println(nil == map[string]int{}) // false
	fmt.Println(nil == []int{})          // false

	// The following lines fail to compile.
	/*
	_ = m == m
	_ = s == s
	_ = m == map[string]int(nil)
	_ = s == []int(nil)
	var x [16][]int
	_ = x == x
	var y [16]map[int]bool
	_ = y == y
	*/
}
</code></pre>
<p></p>
<h3 id="cap-len" class="tmd-header-3">
Check Lengths and Capacities of Container Values
</h3>
<p></p>
<div class="tmd-usual">
Besides the length property, each container value also has a capacity property. The capacity of an array is always equal to the length of the array. The capacity of a non-nil map can be viewed as unlimited. So, in practice, only capacities of slice values are meaningful. The capacity of a slice is always equal to or larger than the length of the slice. The meaning of slice capacities will be explained in the section after next.
</div>
<p></p>
<div class="tmd-usual">
We can use the built-in <code class="tmd-code-span">len</code> function to get the length of a container value, and use the built-in <code class="tmd-code-span">cap</code> function to get the capacity of a container value. Each of the two functions returns an <code class="tmd-code-span">int</code> typed result or an untyped result which default type is <code class="tmd-code-span">int</code>, depending on whether or not the passed argument is a constant expression. As the capacity of any map value is unlimited, the built-in <code class="tmd-code-span">cap</code> function doesn't apply to map values.
</div>
<p></p>
<div class="tmd-usual">
The length and capacity of an array value can never change. The lengths and capacities of all values of an array type always equal to the length of the array type. The length and capacity of a slice value may change at run time. So slices can be viewed as dynamic arrays. Slices are much more flexible than arrays and are used more popularly than arrays in practice.
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var a [5]int
	fmt.Println(len(a), cap(a)) // 5 5
	var s []int
	fmt.Println(len(s), cap(s)) // 0 0
	s, s2 := []int{2, 3, 5}, []bool{}
	fmt.Println(len(s), cap(s))   // 3 3
	fmt.Println(len(s2), cap(s2)) // 0 0
	var m map[int]bool
	fmt.Println(len(m)) // 0
	m, m2 := map[int]bool{1: true, 0: false}, map[int]int{}
	fmt.Println(len(m), len(m2)) // 2 0
}
</code></pre>
<p></p>
<div class="tmd-usual">
The length and capacity of each slice shown in the above specified example value are equal. This is not true for every slice value. We will use some slices whose respective lengths and capacities are not equal in the following sections.
</div>
<p></p>
<h3 id="element-access" class="tmd-header-3">
Retrieve and Modify Container Elements
</h3>
<p></p>
<div class="tmd-usual">
The element associated to key <code class="tmd-code-span">k</code> stored in a container value <code class="tmd-code-span">v</code> is represented with the element indexing syntax form <code class="tmd-code-span">v[k]</code>.
</div>
<p></p>
<div class="tmd-usual">
For a use of <code class="tmd-code-span">v[k]</code>, assume <code class="tmd-code-span">v</code> is an array or slice,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">k</code> is a constant, then it must satisfy <a href="#value-literals">the requirements described above</a> for the indexes in container composite literals. In addition, if <code class="tmd-code-span">v</code> is an array, the <code class="tmd-code-span">k</code> must be smaller than the length of the array.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">k</code> is a non-constant value, it must be a value of any basic integer type. In addition, it must be larger than or equal to zero and smaller than <code class="tmd-code-span">len(v)</code>, otherwise, a run-time panic will occur.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">v</code> is a nil slice, a run-time panic will occur.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
For a use of <code class="tmd-code-span">v[k]</code>, assume <code class="tmd-code-span">v</code> is a map, then <code class="tmd-code-span">k</code> must be assignable to values of the element type of the map type, and
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">k</code> is an interface value whose dynamic type is incomparable, a panic will occur at run time.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">v[k]</code> is used as a destination value in an assignment and <code class="tmd-code-span">v</code> is a nil map, a panic will occur at run time.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">v[k]</code> is used to retrieve the element value corresponding key <code class="tmd-code-span">k</code> in map <code class="tmd-code-span">v</code>, then no panics will occur, even if <code class="tmd-code-span">v</code> is a nil map. (Assume the evaluation of <code class="tmd-code-span">k</code> will not panic.)
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if <code class="tmd-code-span">v[k]</code> is used to retrieve the element value corresponding key <code class="tmd-code-span">k</code> in map <code class="tmd-code-span">v</code>, and the map <code class="tmd-code-span">v</code> doesn't contain an entry with key <code class="tmd-code-span">k</code>, <code class="tmd-code-span">v[k]</code> results in a zero value of the element type of the corresponding map type of <code class="tmd-code-span">v</code>. Generally, <code class="tmd-code-span">v[k]</code> is viewed as a single-value expression. However, when <code class="tmd-code-span">v[k]</code> is used as the only source value expression in an assignment, it can be viewed as a multi-value expression and result a second optional untyped boolean value, which indicates whether or not the map <code class="tmd-code-span">v</code> contains an entry with key <code class="tmd-code-span">k</code>.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
An example of container element accesses and modifications:
</div>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	a := [3]int{-1, 0, 1}
	s := []bool{true, false}
	m := map[string]int{"abc": 123, "xyz": 789}
	fmt.Println (a[2], s[1], m["abc"])    // retrieve
	a[2], s[1], m["abc"] = 999, true, 567 // modify
	fmt.Println (a[2], s[1], m["abc"])    // retrieve

	n, present := m["hello"]
	fmt.Println(n, present, m["hello"]) // 0 false 0
	n, present = m["abc"]
	fmt.Println(n, present, m["abc"]) // 567 true 567
	m = nil
	fmt.Println(m["abc"]) // 0

	// The two lines fail to compile.
	/*
	_ = a[3]  // index 3 out of bounds
	_ = s[-1] // index must be non-negative
	*/

	// Each of the following lines can cause a panic.
	_ = a[n]         // panic: index out of range
	_ = s[n]         // panic: index out of range
	m["hello"] = 555 // panic: assign to entry in nil map
}
</code></pre>
<p></p>
<h3 class="tmd-header-3">
Recall the Internal Structure Definition of Slice Types
</h3>
<p></p>
<div class="tmd-usual">
To understand slice types and values better and explain slices easier, we need to have an impression on the internal structure of slice types. From the last article, <a href="value-part.html">value parts</a>, we learned that the internal structure of slice types defined by the standard Go compiler/runtime is like
</div>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">type _slice struct {
	elements unsafe.Pointer // referencing underlying elements
	len      int            // length
	cap      int            // capacity
}
</code></pre>
<p></p>
<p></p>
<div class="tmd-usual">
The internal structure definitions used by other compilers/runtimes implementations may be not the exact same but would be similar. The following explanations are based on the official slice implementation.
</div>
<p></p>
<div class="tmd-usual">
The above shown internal structure explains the memory layouts of the direct parts of slice values. The <code class="tmd-code-span">len</code> field of the direct part of a slice indicates the length of the slice, and the <code class="tmd-code-span">cap</code> field indicates the capacity of the slice. The following picture depicts one possible memory layout of a slice value.
</div>
<p></p>
<div class="tmd-base tmd-align-center">
<div class="tmd-usual">
<img src="res/slice-internal.png" class="tmd-media"/>
</div>
</div>
<p></p>
<div class="tmd-usual">
Although the underlying memory segment which hosts the elements of a slice may be very large, the slice may be only aware of a sub-segment of the memory segment. For example, in the above picture, the slice is only aware of the middle grey sub-segment of the whole memory segment.
</div>
<p></p>
<div class="tmd-usual">
For the slice depicted in the above picture, the elements from index <code class="tmd-code-span">len</code> to index <code class="tmd-code-span">cap</code> (exclusive) don't belong to the elements of the slice. They are just some redundant element slots for the depicted slice, but they may be effective elements of other slices or another array.
</div>
<p></p>
<div class="tmd-usual">
The next section will explain how to append elements to a base slice and yield a new slice by using the built-in <code class="tmd-code-span">append</code> function. The result slice of an <code class="tmd-code-span">append</code> function call may share starting elements with the base slice or not, depending on the capacity (and length) of the base slice and how many elements are appended.
</div>
<p></p>
<div class="tmd-usual">
When the slice is used as the base slice in an <code class="tmd-code-span">append</code> function call,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if the number of appended elements is larger than the number of the redundant element slots of the base slice, a new underlying memory segment will be allocated for the result slice, thus the result slice and the base slice will not share any elements.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
otherwise, no new underlying memory segments will be allocated for the result slice, and the elements of the base slice also belong to the elements of the result slice. In other words, the two slices share some elements and all of their elements are hosted on the same underlying memory segment.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
The section after next will show a picture which describes both of the two possible cases in appending slice elements.
</div>
<p></p>
<div class="tmd-usual">
There are more routes which lead to the elements of two slices are hosted on the same underlying memory segment. Such as assignments and the below to be introduced subslice operations.
</div>
<p></p>
<div class="tmd-usual">
Note, generally, we can't modify the three fields of a slice value individually, except through the <a href="#modify-slice-length-and-capacity">reflection</a> and <a href="unsafe.html">unsafe</a> ways. In other words, generally, to modify a slice value, its three fields must be modified together. Generally, this is achieved by assigning another slice value (of the same slice type) to the slice which needs to be modified.
</div>
<p></p>
<p></p>
<h3 id="assignment" class="tmd-header-3">
Container Assignments
</h3>
<p></p>
<div class="tmd-usual">
If a map is assigned to another map, then the two maps will share all (underlying) elements. Appending elements into (or deleting elements from) one map will reflect on the other map.
</div>
<p></p>
<div class="tmd-usual">
Like map assignments, if a slice is assigned to another slice, they will share all (underlying) elements. Their respective lengths and capacities equal to each other. However, if the length/capacity of one slice changes later, the change will not reflect on the other slice.
</div>
<p></p>
<div class="tmd-usual">
When an array is assigned to another array, all the elements are copied from the source one to the destination one. The two arrays don't share any elements.
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	m0 := map[int]int{0:7, 1:8, 2:9}
	m1 := m0
	m1[0] = 2
	fmt.Println(m0, m1) // map[0:2 1:8 2:9] map[0:2 1:8 2:9]

	s0 := []int{7, 8, 9}
	s1 := s0
	s1[0] = 2
	fmt.Println(s0, s1) // [2 8 9] [2 8 9]

	a0 := [...]int{7, 8, 9}
	a1 := a0
	a1[0] = 2
	fmt.Println(a0, a1) // [7 8 9] [2 8 9]
}
</code></pre>
<p></p>
<h3 id="element-addition-deletion" class="tmd-header-3">
Append and Delete Container Elements
</h3>
<p></p>
<div class="tmd-usual">
The syntax of appending a key-element pair (an entry) to a map is the same as the syntax of modifying a map element. For example, for a non-nil map value <code class="tmd-code-span">m</code>, the following line
</div>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">m[k] = e
</code></pre>
<p></p>
<div class="tmd-usual">
put the key-element pair <code class="tmd-code-span">(k, e)</code> into the map <code class="tmd-code-span">m</code> if <code class="tmd-code-span">m</code> doesn't contain an entry with key <code class="tmd-code-span">k</code>, or modify the element value associated with <code class="tmd-code-span">k</code> if <code class="tmd-code-span">m</code> contains an entry with key <code class="tmd-code-span">k</code>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
There is a built-in <code class="tmd-code-span">delete</code> function which is used to delete an entry from a map. For example, the following line will delete the entry with key <code class="tmd-code-span">k</code> from the map <code class="tmd-code-span">m</code>. If the map <code class="tmd-code-span">m</code> doesn't contain an entry with key <code class="tmd-code-span">k</code>, it is a no-op, no panics will occur, even if <code class="tmd-code-span">m</code> is a nil map.
</div>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">delete(m, k)
</code></pre>
<p></p>
<div class="tmd-usual">
An example shows how to append (put) entries to and delete entries from maps:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	m := map[string]int{"Go": 2007}
	m["C"] = 1972     // append
	m["Java"] = 1995  // append
	fmt.Println(m)    // map[C:1972 Go:2007 Java:1995]
	m["Go"] = 2009    // modify
	delete(m, "Java") // delete
	fmt.Println(m)    // map[C:1972 Go:2009]
}
</code></pre>
<p></p>
<div class="tmd-usual">
Please note, before Go 1.12, the entry print order of a map is unspecified.
</div>
<p></p>
<div class="tmd-usual">
Array elements can neither be appended nor deleted, though elements of addressable arrays can be modified.
</div>
<p></p>
<div class="tmd-usual">
We can use the built-in <code class="tmd-code-span">append</code> function to append multiple elements into a base slice and result a new slice. The result new slice contains the elements of the base slice and the appended elements. Please note, the base slice is not modified by the <code class="tmd-code-span">append</code> function call. Surely, if we expect (and often in practice), we can assign the result slice to the base slice to modify the base slice.
</div>
<p></p>
<div class="tmd-usual">
There is not a built-in way to delete an element from a slice. We must use the <code class="tmd-code-span">append</code> function and the subslice feature introduced below together to achieve this goal. Slice element deletions and insertions will be demoed in the below <a href="#slice-manipulations">more slice manipulations</a> section. Here, the following example only shows how to use the <code class="tmd-code-span">append</code> function.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
An example showing how to use the <code class="tmd-code-span">append</code> function:
</div>
<p></p>
<pre class="tmd-code line-numbers must-line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	s0 := []int{2, 3, 5}
	fmt.Println(s0, cap(s0)) // [2 3 5] 3
	s1 := append(s0, 7)      // append one element
	fmt.Println(s1, cap(s1)) // [2 3 5 7] 6
	s2 := append(s1, 11, 13) // append two elements
	fmt.Println(s2, cap(s2)) // [2 3 5 7 11 13] 6
	s3 := append(s0)         // &lt;=&gt; s3 := s0
	fmt.Println(s3, cap(s3)) // [2 3 5] 3
	s4 := append(s0, s0...)  // double s0 as s4
	fmt.Println(s4, cap(s4)) // [2 3 5 2 3 5] 6

	s0[0], s1[0] = 99, 789
	fmt.Println(s2[0], s3[0], s4[0]) // 789 99 2
}
</code></pre>
<p></p>
<div class="tmd-usual">
Note, the built-in <code class="tmd-code-span">append</code> function is a <a href="function.html#variadic-function">variadic function</a>. It has two parameters, the second one is a <a href="function.html#variadic-parameter">variadic parameter</a>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Variadic functions will be explained in the article after next. Currently, we only need to know that there are two manners to pass variadic arguments. In the above example, line <span class="tmd-italic">8</span>, line <span class="tmd-italic">10</span> and line <span class="tmd-italic">12</span> use one manner and line <span class="tmd-italic">14</span> uses the other manner. For the former manner, we can pass zero or more element values as the variadic arguments. For the latter manner, we must pass a slice as the only variadic argument and which must be followed by three dots <code class="tmd-code-span">...</code>. We can learn how to call variadic functions from the <a href="function.html#variadic-call">the article after next</a>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
In the above example, line <span class="tmd-italic">14</span> is equivalent to
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">	s4 := append(s0, s0[0], s0[1], s0[2])
</code></pre>
<p></p>
<div class="tmd-usual">
line <span class="tmd-italic">8</span> is equivalent to
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">	s1 := append(s0, []int{7}...)
</code></pre>
<p></p>
<div class="tmd-usual">
and line <span class="tmd-italic">10</span> is equivalent to
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">	s2 := append(s1, []int{11, 13}...)
</code></pre>
<p></p>
<div class="tmd-usual">
For the three-dot <code class="tmd-code-span">...</code> manner, the <code class="tmd-code-span">append</code> function doesn't require the variadic argument must be a slice with the same type as the first slice argument, but their element types must be identical. In other words, the two argument slices must share the same <a href="type-system-overview.html#underlying-type">underlying type</a>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
In the above program,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
the <code class="tmd-code-span">append</code> call at line <span class="tmd-italic">8</span> will allocate a new underlying memory segment for slice <code class="tmd-code-span">s1</code>, for slice <code class="tmd-code-span">s0</code> doesn't have enough redundant element slots to store the new appended element. The same situation is for the <code class="tmd-code-span">append</code> call at line <span class="tmd-italic">14</span>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
the <code class="tmd-code-span">append</code> call at line <span class="tmd-italic">10</span> will not allocate a new underlying memory segment for slice <code class="tmd-code-span">s2</code>, for slice <code class="tmd-code-span">s1</code> has enough redundant element slots to store the new appended elements.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
So, <code class="tmd-code-span">s1</code> and <code class="tmd-code-span">s2</code> share some elements, <code class="tmd-code-span">s0</code> and <code class="tmd-code-span">s3</code> share all elements, and <code class="tmd-code-span">s4</code> doesn't share elements with others. The following picture depicted the statuses of these slices at the end of the above program.
</div>
<p></p>
<div class="tmd-base tmd-align-center">
<div class="tmd-usual">
<img src="res/slice-append.png" class="tmd-media"/>
</div>
</div>
<p></p>
<div class="tmd-usual">
Please note that, when an <code class="tmd-code-span">append</code> call allocate a new underlying memory segment for the result slice, the capacity of the result slice is compiler dependent. For the standard Go compiler, if the capacity of the base slice is small, the capacity of the result slice will be at least the double of the base slice, to avoid allocating underlying memory segments frequently when the result slice is used as the base slices in later possible <code class="tmd-code-span">append</code> calls.
</div>
<p></p>
<div class="tmd-usual">
As mentioned above, we can assign the result slice to the base slice in an <code class="tmd-code-span">append</code> call to append elements into the base slice. For example,
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var s = append([]string(nil), "array", "slice")
	fmt.Println(s)      // [array slice]
	fmt.Println(cap(s)) // 2
	s = append(s, "map")
	fmt.Println(s)      // [array slice map]
	fmt.Println(cap(s)) // 4
	s = append(s, "channel")
	fmt.Println(s)      // [array slice map channel]
	fmt.Println(cap(s)) // 4
}
</code></pre>
<p></p>
<div class="tmd-usual">
The first argument of an <code class="tmd-code-span">append</code> function call can't be an untyped <code class="tmd-code-span">nil</code> (up to Go 1.25).
</div>
<p></p>
<h3 id="make" class="tmd-header-3">
Create Slices and Maps With the Built-in <code class="tmd-code-span">make</code> Function
</h3>
<p></p>
<div class="tmd-usual">
Besides using composite literals to create map and slice values, we can also use the built-in <code class="tmd-code-span">make</code> function to create map and slice values. The built-in <code class="tmd-code-span">make</code> function can't be used to create array values.
</div>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">BTW, the built-in <code class="tmd-code-span">make</code> function can also be used to create channels, which will be explained in the article </span><a href="channel.html"><span class="tmd-italic">channels in Go</span></a><span class="tmd-italic"> later.</span>
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Assume <code class="tmd-code-span">M</code> is a map type and <code class="tmd-code-span">n</code> is an integer, we can use the following two forms to create new maps of type <code class="tmd-code-span">M</code>.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">make(M, n)
make(M)
</code></pre>
<p></p>
<div class="tmd-usual">
The first form creates a new empty map which is allocated with enough space to hold at least <code class="tmd-code-span">n</code> entries without reallocating memory again. The second form only takes one argument, in which case a new empty map with enough space to hold a small number of entries without reallocating memory again. The small number is compiler dependent.
</div>
<p></p>
<div class="tmd-usual">
Note: the second argument <code class="tmd-code-span">n</code> may be negative or zero, in which case it will be ignored.
</div>
<p></p>
<div class="tmd-usual">
Assume <code class="tmd-code-span">S</code> is a slice type, <code class="tmd-code-span">length</code> and <code class="tmd-code-span">capacity</code> are two non-negative integers, <code class="tmd-code-span">length</code> is not larger than <code class="tmd-code-span">capacity</code>, we can use the following two forms to create new slices of type <code class="tmd-code-span">S</code>. (The types of <code class="tmd-code-span">length</code> and <code class="tmd-code-span">capacity</code> are not required to be identical.)
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">make(S, length, capacity)
make(S, length)
</code></pre>
<p></p>
<div class="tmd-usual">
The first form creates a new slice with the specified length and capacity. The second form only takes two arguments, in which case the capacity of the new created slice is the same as its length.
</div>
<p></p>
<div class="tmd-usual">
All the elements in the result slice of a <code class="tmd-code-span">make</code> function call are initialized as the zero value (of the slice element type).
</div>
<p></p>
<div class="tmd-usual">
An example on how to use the built-in <code class="tmd-code-span">make</code> function to create maps and slices:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	// Make new maps.
	fmt.Println(make(map[string]int)) // map[]
	m := make(map[string]int, 3)
	fmt.Println(m, len(m)) // map[] 0
	m["C"] = 1972
	m["Go"] = 2009
	fmt.Println(m, len(m)) // map[C:1972 Go:2009] 2

	// Make new slices.
	s := make([]int, 3, 5)
	fmt.Println(s, len(s), cap(s)) // [0 0 0] 3 5
	s = make([]int, 2)
	fmt.Println(s, len(s), cap(s)) // [0 0] 2 2
}
</code></pre>
<p></p>
<h3 id="new" class="tmd-header-3">
Allocate Containers With the Built-in <code class="tmd-code-span">new</code> Function
</h3>
<p></p>
<div class="tmd-usual">
From the article <a href="pointer.html">pointers in Go</a>, we learned that we can also call the built-in <code class="tmd-code-span">new</code> function to allocate a value of any type and get a pointer which references the allocated value. The allocated value is a zero value of its type. For this reason, it is a nonsense to use <code class="tmd-code-span">new</code> function to create map and slice values.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
It is not totally a nonsense to allocate a zero value of an array type with the built-in <code class="tmd-code-span">new</code> function. However, it is seldom to do this in practice, for it is more convenient to use composite literals to allocate arrays.
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	m := *new(map[string]int)   // &lt;=&gt; var m map[string]int
	fmt.Println(m == nil)       // true
	s := *new([]int)            // &lt;=&gt; var s []int
	fmt.Println(s == nil)       // true
	a := *new([5]bool)          // &lt;=&gt; var a [5]bool
	fmt.Println(a == [5]bool{}) // true
}
</code></pre>
<p></p>
<h3 id="addressability" class="tmd-header-3">
Addressability of Container Elements
</h3>
<p></p>
<div class="tmd-usual">
Following are some facts about the addressabilities of container elements.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Elements of addressable array values are also addressable. Elements of unaddressable array values are also unaddressable. The reason is each array value only consists of one <a href="value-part.html">direct part</a>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Elements of any slice value are always addressable, whether or not that slice value is addressable. This is because the elements of a slice are stored in the underlying (indirect) value part of the slice and the underlying part is always hosted on an allocated memory segment.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Elements of map values are always unaddressable. Please read <a href="unofficial-faq.html#maps-are-unaddressable">this FAQ item</a> for reasons.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
For example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	a := [5]int{2, 3, 5, 7}
	s := make([]bool, 2)
	pa2, ps1 := &amp;a[2], &amp;s[1]
	fmt.Println(*pa2, *ps1) // 5 false
	a[2], s[1] = 99, true
	fmt.Println(*pa2, *ps1) // 99 true
	ps0 := &amp;[]string{"Go", "C"}[0]
	fmt.Println(*ps0) // Go

	m := map[int]bool{1: true}
	_ = m
	// The following lines fail to compile.
	/*
	_ = &amp;[3]int{2, 3, 5}[0]
	_ = &amp;map[int]bool{1: true}[1]
	_ = &amp;m[1]
	*/
}
</code></pre>
<p></p>
<div class="tmd-usual">
Unlike most other unaddressable values, which direct parts can not be modified, the direct part of a map element values can be modified, but can only be modified (overwritten) as a whole. For most kinds of element types, this is not a big issue. However, if the element type of map type is an array type or struct type, things become some counter-intuitive.
</div>
<p></p>
<div class="tmd-usual">
From the last article, <a href="value-part.html">value parts</a>, we learned that each of struct and array values only consists of one direct part. So
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if the element type of a map is a struct type, we can not individually modify each field of an element (which is a struct) of the map.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if the element type of a map is an array type, we can not individually modify each element of an element (which is an array) of the map.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	type T struct{age int}
	mt := map[string]T{}
	mt["John"] = T{age: 29} // modify it as a whole
	ma := map[int][5]int{}
	ma[1] = [5]int{1: 789} // modify it as a whole

	// The following two lines fail to compile,
	// for map elements can be modified partially.
	/*
	ma[1][1] = 123      // error
	mt["John"].age = 30 // error
	*/

	// Accesses are okay.
	fmt.Println(ma[1][1])       // 789
	fmt.Println(mt["John"].age) // 29
}
</code></pre>
<p></p>
<div class="tmd-usual">
To make any expected modification work in the above example, the corresponding map element should be saved in a temporary variable firstly, then the temporary variable is modified as needed, in the end the corresponding map element is overwritten by the temporary variable. For example,
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	type T struct{age int}
	mt := map[string]T{}
	mt["John"] = T{age: 29}
	ma := map[int][5]int{}
	ma[1] = [5]int{1: 789}

	t := mt["John"] // a temporary copy
	t.age = 30
	mt["John"] = t // overwrite it back

	a := ma[1] // a temporary copy
	a[1] = 123
	ma[1] = a // overwrite it back

	fmt.Println(ma[1][1], mt["John"].age) // 123 30
}
</code></pre>
<p></p>
<div class="tmd-usual">
Note: the just mentioned limit <a href="https://github.com/golang/go/issues/3117">might be lifted later</a>.
</div>
<p></p>
<p></p>
<h3 id="subslice" class="tmd-header-3">
Derive Slices From Arrays and Slices
</h3>
<p></p>
<div class="tmd-usual">
We can derive a new slice from another (base) slice or a base addressable array by using the subslice syntax forms (Go specification calls them as slice syntax forms). The process is also often called as reslicing. The elements of the derived slice and the base array or slice are hosted on the same memory segment. In other words, the derived slice and the base array or slice may share some contiguous elements.
</div>
<p></p>
<div class="tmd-usual">
There are two subslice syntax forms (<code class="tmd-code-span">baseContainer</code> is an array or slice):
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">baseContainer[low : high]       // two-index form
baseContainer[low : high : max] // three-index form
</code></pre>
<p></p>
<div class="tmd-usual">
The two-index form is equivalent to
</div>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">baseContainer[low : high : cap(baseContainer)]
</code></pre>
<p></p>
<div class="tmd-usual">
So the two-index form is a special case of the three-index form. The two-index form is used much more popularly than the three-index form in practice.
</div>
<p></p>
<div class="tmd-usual">
Note, the three-index form is only supported since Go 1.2.
</div>
<p></p>
<div class="tmd-usual">
In a subslice expression, the <code class="tmd-code-span">low</code>, <code class="tmd-code-span">high</code> and <code class="tmd-code-span">max</code> indexes must satisfy the following relation requirements.
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">// two-index form
0 &lt;= low &lt;= high &lt;= cap(baseContainer)

// three-index form
0 &lt;= low &lt;= high &lt;= max &lt;= cap(baseContainer)
</code></pre>
<p></p>
<div class="tmd-usual">
Indexes not satisfying these requirements may make the subslice expression fail to compile at compile time or panic at run time, depending on the base container type kind and whether or not the indexes are constants.
</div>
<p></p>
<div class="tmd-usual">
Note,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
the <code class="tmd-code-span">low</code> and <code class="tmd-code-span">high</code> indexes can be both larger than <code class="tmd-code-span">len(baseContainer)</code>, as long as the above relations are all satisfied. But the two indexes must not be larger than <code class="tmd-code-span">cap(baseContainer)</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
a subslice expression will not cause a panic if <code class="tmd-code-span">baseContainer</code> is a nil slice and all indexes used in the expression are zero. The result slice derived from a nil slice is still a nil slice.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
The length of the result derived slice is equal to <code class="tmd-code-span">high - low</code>, and the capacity of the result derived slice is equal to <code class="tmd-code-span">max - low</code>. The length of a derived slice may be larger than the base container, but the capacity will never be larger than the base container.
</div>
<p></p>
<div class="tmd-usual">
In practice, for simplicity, we often omitted some indexes in subslice syntax forms. The omission rules are:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if the <code class="tmd-code-span">low</code> index is equal to zero, it can be omitted, either for two-index or three-index forms.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if the <code class="tmd-code-span">high</code> is equal to <code class="tmd-code-span">len(baseContainer)</code>, it can be omitted, but only for two-index forms.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
the <code class="tmd-code-span">max</code> can never be omitted in three-index forms.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
For example, the following expressions are equivalent.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">baseContainer[0 : len(baseContainer)]
baseContainer[: len(baseContainer)]
baseContainer[0 :]
baseContainer[:]
baseContainer[0 : len(baseContainer) : cap(baseContainer)]
baseContainer[: len(baseContainer) : cap(baseContainer)]
</code></pre>
<p></p>
<div class="tmd-usual">
An example of using subslice syntax forms:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	a := [...]int{0, 1, 2, 3, 4, 5, 6}
	s0 := a[:]     // &lt;=&gt; s0 := a[0:7:7]
	s1 := s0[:]    // &lt;=&gt; s1 := s0
	s2 := s1[1:3]  // &lt;=&gt; s2 := a[1:3]
	s3 := s1[3:]   // &lt;=&gt; s3 := s1[3:7]
	s4 := s0[3:5]  // &lt;=&gt; s4 := s0[3:5:7]
	s5 := s4[:2:2] // &lt;=&gt; s5 := s0[3:5:5]
	s6 := append(s4, 77)
	s7 := append(s5, 88)
	s8 := append(s7, 66)
	s3[1] = 99
	fmt.Println(len(s2), cap(s2), s2) // 2 6 [1 2]
	fmt.Println(len(s3), cap(s3), s3) // 4 4 [3 99 77 6]
	fmt.Println(len(s4), cap(s4), s4) // 2 4 [3 99]
	fmt.Println(len(s5), cap(s5), s5) // 2 2 [3 99]
	fmt.Println(len(s6), cap(s6), s6) // 3 4 [3 99 77]
	fmt.Println(len(s7), cap(s7), s7) // 3 4 [3 4 88]
	fmt.Println(len(s8), cap(s8), s8) // 4 4 [3 4 88 66]
}
</code></pre>
<p></p>
<div class="tmd-usual">
The following picture depicts the final memory layouts of the array and slice values used in the above example.
</div>
<p></p>
<div class="tmd-base tmd-align-center">
<div class="tmd-usual">
<img src="res/slice-subslice-2.png" class="tmd-media"/>
</div>
</div>
<p></p>
<div class="tmd-usual">
From the picture, we know that the elements of slice <code class="tmd-code-span">s7</code> and <code class="tmd-code-span">s8</code> are hosted on a different underlying memory segment than the other containers. The elements of the other slices are hosted on the same memory segment hosting the array <code class="tmd-code-span">a</code>.
</div>
<p></p>
<div class="tmd-usual">
Please note that, subslice operations may cause kind-of memory leaking. For example, half of the memory allocated for the return slice of a call to the following function will be wasted unless the returned slice becomes unreachable (if no other slices share the underlying element memory segment with the returned slice).
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">func f() []int {
	s := make([]int, 10, 100)
	return s[50:60]
}
</code></pre>
<p></p>
<div class="tmd-usual">
Please note that, in the above function, the lower index (<code class="tmd-code-span">50</code>) is larger than the length (<code class="tmd-code-span">10</code>) of <code class="tmd-code-span">s</code>, which is allowed.
</div>
<p></p>
<h3 id="slice-to-array-pointer" class="tmd-header-3">
Convert Slice to Array Pointer
</h3>
<p></p>
<div class="tmd-usual">
Since Go 1.17, a slice may be converted to an array pointer. In such a conversion, if the length of the base array type of the pointer type is larger than the length of the slice, a panic occurs.
</div>
<p></p>
<div class="tmd-usual">
An example:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

type S []int
type A [2]int
type P *A

func main() {
	var x []int
	var y = make([]int, 0)
	var x0 = (*[0]int)(x) // okay, x0 == nil
	var y0 = (*[0]int)(y) // okay, y0 != nil
	_, _ = x0, y0

	var z = make([]int, 3, 5)
	var _ = (*[3]int)(z) // okay
	var _ = (*[2]int)(z) // okay
	var _ = (*A)(z)      // okay
	var _ = P(z)         // okay

	var w = S(z)
	var _ = (*[3]int)(w) // okay
	var _ = (*[2]int)(w) // okay
	var _ = (*A)(w)      // okay
	var _ = P(w)         // okay

	var _ = (*[4]int)(z) // will panic
}
</code></pre>
<p></p>
<h3 id="slice-to-array" class="tmd-header-3">
Convert Slice to Array
</h3>
<p></p>
<p></p>
<div class="tmd-usual">
Since Go 1.20, a slice may be converted to an array. In such a conversion, if the length of the array type is larger than the length of the slice, a panic occurs. The slice and the result array don't share any element.
</div>
<p></p>
<div class="tmd-usual">
An example:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var s = []int{0, 1, 2, 3}
	var a = [3]int(s[1:])
	s[2] = 9
	fmt.Println(s) // [0 1 9 3]
	fmt.Println(a) // [1 2 3]
	
	_ = [3]int(s[:2]) // panic
}
</code></pre>
<p></p>
<h3 id="copy-slice-elements" class="tmd-header-3">
Copy Slice Elements With the Built-in <code class="tmd-code-span">copy</code> Function
</h3>
<p></p>
<div class="tmd-usual">
We can use the built-in <code class="tmd-code-span">copy</code> function to copy elements from one slice to another, the types of the two slices are not required to be identical, but their element types must be identical. In other words, the two argument slices must share the same underlying type. The first parameter of the <code class="tmd-code-span">copy</code> function is the destination slice and the second one is the source slice. The two parameters can overlap some elements. <code class="tmd-code-span">copy</code> function returns the number of elements copied, which will be the smaller one of the lengths of the two parameters.
</div>
<p></p>
<div class="tmd-usual">
With the help of the subslice syntax, we can use the <code class="tmd-code-span">copy</code> function to copy elements between two arrays or between an array and a slice.
</div>
<p></p>
<div class="tmd-usual">
An example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	type Ta []int
	type Tb []int
	dest := Ta{1, 2, 3}
	src := Tb{5, 6, 7, 8, 9}
	n := copy(dest, src)
	fmt.Println(n, dest) // 3 [5 6 7]
	n = copy(dest[1:], dest)
	fmt.Println(n, dest) // 2 [5 5 6]

	a := [4]int{} // an array
	n = copy(a[:], src)
	fmt.Println(n, a) // 4 [5 6 7 8]
	n = copy(a[:], a[2:])
	fmt.Println(n, a) // 2 [7 8 7 8]
}
</code></pre>
<p></p>
<p></p>
<div class="tmd-usual">
Note, as a special case, the built-in <code class="tmd-code-span">copy</code> function can be used to <a href="string.html#use-string-as-byte-slice">copy bytes from a string to a byte slice</a>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Neither of the two arguments of a <code class="tmd-code-span">copy</code> function call can be an untyped <code class="tmd-code-span">nil</code> value (up to Go 1.25).
</div>
<p></p>
<h3 id="iteration" class="tmd-header-3">
Container Element Iterations
</h3>
<p></p>
<div class="tmd-usual">
In Go, keys and elements of a container value can be iterated with the following syntax:
</div>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">for key, element = range aContainer {
	// use key and element ...
}
</code></pre>
<p></p>
<div class="tmd-usual">
where <code class="tmd-code-span">for</code> and <code class="tmd-code-span">range</code> are two keywords, <code class="tmd-code-span">key</code> and <code class="tmd-code-span">element</code> are called iteration variables. If <code class="tmd-code-span">aContainer</code> is a slice or an array (or an array pointer, see below), then the type of <code class="tmd-code-span">key</code> must be built-in type <code class="tmd-code-span">int</code>.
</div>
<p></p>
<div class="tmd-usual">
The assignment sign <code class="tmd-code-span">=</code> can be a short variable declaration sign <code class="tmd-code-span">:=</code>, in which case the two iteration variables are both two new declared variables which are only visible within the <code class="tmd-code-span">for-range</code> code block body, if <code class="tmd-code-span">aContainer</code> is a slice or an array (or an array pointer), then the type of <code class="tmd-code-span">key</code> is deduced as <code class="tmd-code-span">int</code>.
</div>
<p></p>
<div class="tmd-usual">
Like the traditional <code class="tmd-code-span">for</code> loop block, each <code class="tmd-code-span">for-range</code> loop block creates two code blocks, an implicit one and an explicit one which is formed by using <code class="tmd-code-span">{}</code>. The explicit one is nested in the implicit one.
</div>
<p></p>
<div class="tmd-usual">
Like <code class="tmd-code-span">for</code> loop blocks, <code class="tmd-code-span">break</code> and <code class="tmd-code-span">continue</code> statements can also be used in <code class="tmd-code-span">for-range</code> loop blocks,
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	m := map[string]int{"C": 1972, "C++": 1983, "Go": 2009}
	for lang, year := range m {
		fmt.Printf("%v: %v \n", lang, year)
	}

	a := [...]int{2, 3, 5, 7, 11}
	for i, prime := range a {
		fmt.Printf("%v: %v \n", i, prime)
	}

	s := []string{"go", "defer", "goto", "var"}
	for i, keyword := range s {
		fmt.Printf("%v: %v \n", i, keyword)
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
The form <code class="tmd-code-span">for-range</code> code block syntax has several variants:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">// Ignore the key iteration variable.
for _, element = range aContainer {
	// ...
}

// Ignore the element iteration variable.
for key, _ = range aContainer {
	element = aContainer[key]
	// ...
}

// The element iteration variable is omitted.
// This form is equivalent to the last one.
for key = range aContainer {
	element = aContainer[key]
	// ...
}

// Ignore both the key and element iteration variables.
for _, _ = range aContainer {
	// This variant is not much useful.
}

// Both the key and element iteration variables are
// omitted. This form is equivalent to the last one.
for range aContainer {
	// This variant is not much useful.
}
</code></pre>
<p></p>
<div class="tmd-usual">
Iterating over nil maps or nil slices is allowed. Such iterations are no-ops.
</div>
<p></p>
<div class="tmd-usual">
Some details about iterations over maps are listed here.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
For a map, the entry order in an iteration is not guaranteed to be the same as the next iteration, even if the map is not modified between the two iterations. By Go specification, the order is unspecified (kind-of randomized).
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
If a map entry (a key-element pair) which has not yet been reached is removed during an iteration, then the entry will not iterated in the same iteration for sure.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
If a map entry is created during an iteration, that entry may be iterated during the same iteration, or not.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
If it is promised that there are no other goroutines manipulating a map <code class="tmd-code-span">m</code>, then the following code is guaranteed to clear all entries (but the ones with keys as <code class="tmd-code-span">NaN</code>) stored in the map <code class="tmd-code-span">m</code>:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">for key := range m {
	delete(m, key)
}
</code></pre>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(Note: Go 1.21 introduced a </span><a href="#clear"><span class="tmd-italic"><code class="tmd-code-span">clear</code> builtin function</span></a><span class="tmd-italic">, which may be used to clear all entries of a map, including those with keys as <code class="tmd-code-span">NaN</code>.)</span>
</div>
<p></p>
<div class="tmd-usual">
Surely, array and slice elements can also be iterated by using the traditional <code class="tmd-code-span">for</code> loop block:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">for i := 0; i &lt; len(anArrayOrSlice); i++ {
	// ... use anArrayOrSlice[i]
}
</code></pre>
<p></p>
<div class="tmd-usual">
For a <code class="tmd-code-span">for-range</code> loop block (whether <code class="tmd-code-span">=</code> or <code class="tmd-code-span">:=</code> before <code class="tmd-code-span">range</code>)
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">for key, element = range aContainer {...}
</code></pre>
<p></p>
<div class="tmd-usual">
there are two important facts.
</div>
<p></p>
<p></p>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
The ranged container is <span class="tmd-bold">a copy</span> of <code class="tmd-code-span">aContainer</code>. Please note, <a href="value-part.html#about-value-copy">only the direct part of <code class="tmd-code-span">aContainer</code> is copied</a>. The container copy is anonymous, so there are no ways to modify it.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
If the <code class="tmd-code-span">aContainer</code> is an array, then the modifications made on the array elements during the iteration will not be reflected to the iteration variables. The reason is that the copy of the array doesn't share elements with the array.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
If the <code class="tmd-code-span">aContainer</code> is a slice or map, then the modifications made on the slice or map elements during the iteration will be reflected to the iteration variables. The reason is that the clone of the slice (or map) shares all elements (entries) with the slice (or map).
</div>
</li>
</ul>
<p></p>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
A key-element pair of the copy of <code class="tmd-code-span">aContainer</code> will be assigned (copied) to the iteration variable pair at each iteration step, so the modifications made on <span class="tmd-bold">the direct parts</span> of the iteration variables will not be reflected to the elements (and keys for maps) stored in <code class="tmd-code-span">aContainer</code>. (For this fact, and as using <code class="tmd-code-span">for-range</code> loop blocks is the only way to iterate map keys and elements, it is recommended not to use large-size types as map key and element types, to avoid large copy burdens.)
</div>
</li>
</ol>
<p></p>
<div class="tmd-usual">
An example which proves the first and second facts.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	type Person struct {
		name string
		age  int
	}
	persons := [2]Person {{"Alice", 28}, {"Bob", 25}}
	for i, p := range persons {
		fmt.Println(i, p)

		// This modification has no effects on
		// the iteration, for the ranged array
		// is a copy of the persons array.
		persons[1].name = "Jack"

		// This modification has not effects on
		// the persons array, for p is just a
		// copy of a copy of one persons element.
		p.age = 31
	}
	fmt.Println("persons:", &amp;persons)
}
</code></pre>
<p></p>
<div class="tmd-usual">
The output:
</div>
<pre class="tmd-code output">
0 {Alice 28}
1 {Bob 25}
persons: &amp;[{Alice 28} {Jack 25}]
</pre>
<p></p>
<div class="tmd-usual">
If we change the array in the above to a slice, then the modification on the slice during the iteration has effects on the iteration, but the modification on the iteration variable still has no effects on the slice.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">...

	// A slice.
	persons := []Person {{"Alice", 28}, {"Bob", 25}}
	for i, p := range persons {
		fmt.Println(i, p)

		// Now this modification has effects
		// on the iteration.
		persons[1].name = "Jack"

		// This modification still has not
		// any real effects.
		p.age = 31
	}
	fmt.Println("persons:", &amp;persons)
}
</code></pre>
<p></p>
<div class="tmd-usual">
The output becomes to:
</div>
<pre class="tmd-code output">
0 {Alice 28}
1 {Jack 25}
persons: &amp;[{Alice 28} {Jack 25}]
</pre>
<p></p>
<div class="tmd-usual">
The following example proves the second fact.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	m := map[int]struct{ dynamic, strong bool } {
		0: {true, false},
		1: {false, true},
		2: {false, false},
	}
	
	for _, v := range m {
		// This following line has no effects on the map m.
		v.dynamic, v.strong = true, true
	}
	
	fmt.Println(m[0]) // {true false}
	fmt.Println(m[1]) // {false true}
	fmt.Println(m[2]) // {false false}
}
</code></pre>
<p></p>
<div class="tmd-usual">
The cost of a slice or map assignment is small, but the cost of an array assignment is large if the size of the array type is large. So, generally, it is not a good idea to range over a large array. We can range over a slice derived from the array, or range over a pointer to the array (see the next section for details).
</div>
<p></p>
<div class="tmd-usual">
For an array or slice, if the size of its element type is large, then, generally, it is also not a good idea to use the second iteration variable to store the iterated element at each loop step. For such arrays and slices, we should use the one-iteration-variable <code class="tmd-code-span">for-range</code> loop variant or the traditional <code class="tmd-code-span">for</code> loop to iterate their elements. In the following example, the loop in function <code class="tmd-code-span">fa</code> is much less efficient than the loop in function <code class="tmd-code-span">fb</code>.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">type Buffer struct {
	start, end int
	data       [1024]byte
}

func fa(buffers []Buffer) int {
	numUnreads := 0
	for _, buf := range buffers {
		numUnreads += buf.end - buf.start
	}
	return numUnreads
}

func fb(buffers []Buffer) int {
	numUnreads := 0
	for i := range buffers {
		numUnreads += buffers[i].end - buffers[i].start
	}
	return numUnreads
}
</code></pre>
<p></p>
<div class="tmd-usual">
Prior to Go 1.22, when a <code class="tmd-code-span">for-range</code> loop block (note the sign before before <code class="tmd-code-span">range</code> is <code class="tmd-code-span">:=</code>)
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">for key, element := range aContainer {...}
</code></pre>
<p></p>
<div class="tmd-usual">
is executed, all key-element pairs will be assigned to <span class="tmd-bold">the same</span> iteration variable instance pair. However, since Go 1.22, each key-element pair will be assigned to a <span class="tmd-bold">distinctive</span> iteration variable instance pair (a.k.a. a distinctive instance will be created for each iteration variable in each loop iteration).
</div>
<p></p>
<div class="tmd-usual">
The following example shows the behavior differences between 1.21- and 1.22+ Go versions.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">// forrange1.go
package main

import "fmt"

func main() {
	for i, n := range []int{0, 1, 2} {
		defer func() {
			fmt.Println(i, n)
		}()
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
By using different Go Toolchain versions to run the code (<a href="https://go101.org/apps-and-libs/gotv.html">gotv</a> is a tool used to manage and use multiple coexisting installations of official Go toolchain versions), we will get different outputs:
</div>
<p></p>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">$ gotv 1.21. run forrange1.go
[Run]: $HOME/.cache/gotv/tag_go1.21.8/bin/go run forrange1.go
2 2
2 2
2 2
$ gotv 1.22. run forrange1.go
[Run]: $HOME/.cache/gotv/tag_go1.22.1/bin/go run forrange1.go
2 2
1 1
0 0
</code></pre>
<p></p>
<div class="tmd-usual">
Another example:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">// forrange2.go
package main

import "fmt"

func main() {
	var m = map[*int]uint32{}
	for i, n := range []int{1, 2, 3} {
		m[&amp;i]++
		m[&amp;n]++
	}
	fmt.Println(len(m))
}
</code></pre>
<p></p>
<div class="tmd-usual">
Use different Go Toolchain versions, we will get the following outputs:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">$ gotv 1.21. run forrange2.go
[Run]: $HOME/.cache/gotv/tag_go1.21.8/bin/go run forrange2.go
2
$ gotv 1.22. run forrange2.go
[Run]: $HOME/.cache/gotv/tag_go1.22.1/bin/go run forrange2.go
6
</code></pre>
<p></p>
<div class="tmd-usual">
Therefore, this is a semantic change which breaks backward compatibility. But the new semantic is actually more in line with people's expectations. And in theory, no old code that was found to be logically correct would be broken by this change.
</div>
<p></p>
<h3 id="use-pointer-as-array" class="tmd-header-3">
Use Array Pointers as Arrays
</h3>
<p></p>
<div class="tmd-usual">
In many scenarios, we can use a pointer to an array as the array.
</div>
<p></p>
<div class="tmd-usual">
We can range over a pointer to an array to iterate the elements of the array. For arrays with large lengths, this way is much more efficient, for copying a pointer is much more efficient than copying a large-size array. In the following example, the two loop blocks are equivalent and both are efficient.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var a [100]int

	// Copying a pointer is cheap.
	for i, n := range &amp;a {
		fmt.Println(i, n)
	}

	// Copying a slice is cheap.
	for i, n := range a[:] {
		fmt.Println(i, n)
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
If the second iteration in a <code class="tmd-code-span">for-range</code> loop is neither ignored nor omitted, then range over a nil array pointer will panic. In the following example, each of the first two loop blocks will print five indexes, however, the last one will produce a panic.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var p *[5]int // nil

	for i, _ := range p { // okay
		fmt.Println(i)
	}

	for i := range p { // okay
		fmt.Println(i)
	}

	for i, n := range p { // panic
		fmt.Println(i, n)
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
Array pointers can also used to index array elements. Indexing array elements through a nil array pointer produces a panic.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	a := [5]int{2, 3, 5, 7, 11}
	p := &amp;a
	p[0], p[1] = 17, 19
	fmt.Println(a) // [17 19 5 7 11]
	p = nil
	_ = p[0] // panic
}
</code></pre>
<p></p>
<div class="tmd-usual">
We can also derive slices from array pointers. Deriving slices from a nil array pointer produce a panic.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	pa := &amp;[5]int{2, 3, 5, 7, 11}
	s := pa[1:3]
	fmt.Println(s) // [3 5]
	pa = nil
	s = pa[0:0] // panic
	// Should this line execute, it also panics.
	_ = (*[0]byte)(nil)[:]
}
</code></pre>
<p></p>
<div class="tmd-usual">
We can also pass array pointers as the arguments of the built-in <code class="tmd-code-span">len</code> and <code class="tmd-code-span">cap</code> functions. Nil array pointer arguments for the two functions will not produce panics.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">var pa *[5]int // == nil
fmt.Println(len(pa), cap(pa)) // 5 5
</code></pre>
<p></p>
<h3 id="clear" class="tmd-header-3">
Use the built-in <code class="tmd-code-span">clear</code> function to clear map entries and reset slice elements
</h3>
<p></p>
<div class="tmd-usual">
Go 1.21 introduced <code class="tmd-code-span">clear</code> builtin function. This function is used to clear map entries and reset slice elements.
</div>
<p></p>
<div class="tmd-usual">
An example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
s := []int{1, 2, 3}
clear(s)
fmt.Println(s) // [0 0 0]

a := [4]int{5, 6, 7, 8}
clear(a[1:3])
fmt.Println(a) // [5 0 0 8]

m := map[float64]float64{}
x := 0.0
m[x] = x
x /= x // x is NaN now
m[x] = x
fmt.Println(len(m)) // 2
for k := range m {
delete(m, k)
}
fmt.Println(len(m)) // 1
clear(m)
fmt.Println(len(m)) // 0
}
</code></pre>
<p></p>
<div class="tmd-usual">
We can find that the <code class="tmd-code-span">clear</code> function can even delete map entries with keys as <code class="tmd-code-span">NaN</code>.
</div>
<p></p>
<h3 id="memclr" class="tmd-header-3">
The <code class="tmd-code-span">memclr</code> Optimization
</h3>
<p></p>
<div class="tmd-usual">
The Go standard Go compiler makes several optimizations so that it will convert loops with certain pattterns into internal <code class="tmd-code-span">memclr</code> calls. Before Go 1.21, we can make use of these optimizations to reset array/slice elements and clear map entries.
</div>
<p></p>
<div class="tmd-usual">
These optimizations (and many more others) are collected in <a href="https://go101.org/optimizations/101.html">Go Optimizations 101</a> book.
</div>
<p></p>
<p></p>
<h3 id="compile-time-evaluation" class="tmd-header-3">
Calls to the Built-in <code class="tmd-code-span">len</code> and <code class="tmd-code-span">cap</code> Functions May Be Evaluated at Compile Time
</h3>
<p></p>
<div class="tmd-usual">
If the argument passed to a call of the built-in function <code class="tmd-code-span">len</code> or <code class="tmd-code-span">cap</code> function is an array or an array pointer value, then the call is evaluated at compile time and the result of the call is a typed constant with type as the built-in type <code class="tmd-code-span">int</code>. The result can be bound to named constants.
</div>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

var a [5]int
var p *[7]string

// N and M are both typed constants.
const N = len(a)
const M = cap(p)

func main() {
	fmt.Println(N) // 5
	fmt.Println(M) // 7
}
</code></pre>
<p></p>
<div class="tmd-usual">
There are more scenarios in which calls to the built-in function <code class="tmd-code-span">len</code> and <code class="tmd-code-span">cap</code> functions are evaluated at compile time. Please read the <a href="https://go101.org/details-and-tips/101.html">Go Details &amp; Tips 101</a> book for such cases.
</div>
<p></p>
<p></p>
<h3 id="modify-slice-length-and-capacity" class="tmd-header-3">
Modify the Length and Capacity Properties of a Slice Individually
</h3>
<p></p>
<div class="tmd-usual">
Above has mentioned, generally, the length and capacity of a slice value can't be modified individually. A slice value can only be overwritten as a whole by assigning another slice value to it. However, we can modify the length and capacity of a slice individually by using reflections. Reflection will be explained in <a href="reflection.html">a later article</a> in detail.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import (
	"fmt"
	"reflect"
)

func main() {
	s := make([]int, 2, 6)
	fmt.Println(len(s), cap(s)) // 2 6

	reflect.ValueOf(&amp;s).Elem().SetLen(3)
	fmt.Println(len(s), cap(s)) // 3 6

	reflect.ValueOf(&amp;s).Elem().SetCap(5)
	fmt.Println(len(s), cap(s)) // 3 5
}
</code></pre>
<p></p>
<div class="tmd-usual">
The second argument passed to the <code class="tmd-code-span">reflect.SetLen</code> function must not be larger than the current capacity of the argument slice <code class="tmd-code-span">s</code>. The second argument passed to the <code class="tmd-code-span">reflect.SetCap</code> function must not be smaller than the current length of the argument slice <code class="tmd-code-span">s</code> and larger than the current capacity of the argument slice <code class="tmd-code-span">s</code>. Otherwise, a panic will occur.
</div>
<p></p>
<div class="tmd-usual">
The reflection way is very inefficient, it is slower than a slice assignment.
</div>
<p></p>
<h3 id="slice-manipulations" class="tmd-header-3">
More Slice Manipulations
</h3>
<p></p>
<div id="delete-slice-elements" class="tmd-usual tmd-dropcap">

</div>
<p></p>
<div id="delete-one-slice-element" class="tmd-usual tmd-dropcap">

</div>
<p></p>
<div class="tmd-usual">
Go doesn't support more built-in slice operations, such as slice clone, element deletion and insertion. We must compose the built-in ways to achieve those operations.
</div>
<p></p>
<div class="tmd-usual">
Please read the "Arrays and Slices" chapter in the <a href="https://go101.org/optimizations/101.html">Go Optimizations 101</a> book for how to efficiently make such operations.
</div>
<p></p>
<p></p>
<h3 class="tmd-header-3">
Use Maps to Simulate Sets
</h3>
<p></p>
<div class="tmd-usual">
Go doesn't support built-in <span class="tmd-bold">set</span> types. However, it is easy to use a map type to simulate a set type. In practice, we often use the map type <code class="tmd-code-span">map[K]struct{}</code> to simulate a set type with element type <code class="tmd-code-span">K</code>. The size of the map element type <code class="tmd-code-span">struct{}</code> is zero, elements of values of such map types don't occupy memory space.
</div>
<p></p>
<h3 class="tmd-header-3">
Container Related Operations Are Not Synchronized Internally
</h3>
<p></p>
<div class="tmd-usual">
Please note that, all container operations are not synchronized internally. Without making using of any data synchronization technique, it is okay for multiple goroutines to read a container concurrently, but it is not okay for multiple goroutines to manipulate a container concurrently and at least one goroutine modifies the container. The latter case will cause data races, even make goroutines panic. We must synchronize the container operations manually. Please read the articles on <a href="concurrent-synchronization-overview.html">data synchronizations</a> for details.
</div>
<p></p>
<p></p>
</div>
